package com.gitee.empty_null.orm.repository;

import com.gitee.empty_null.orm.converter.DelegateConverter;
import com.gitee.empty_null.orm.converter.RegisteredClientConverter;
import com.gitee.empty_null.orm.entity.AuthorizationEntity;
import com.gitee.empty_null.orm.entity.RegisteredClientEntity;
import com.gitee.empty_null.orm.service.IRegisteredClientService;
import com.mybatisflex.core.activerecord.MapperModel;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;

import java.util.Optional;

/**
 * @author xuhainan
 * @date 2024/1/22 14:47
 * @region hefei
 */
public class FlexRegisteredClientRepository implements RegisteredClientRepository {

    private final IRegisteredClientService registeredClientService;
    private final DelegateConverter<RegisteredClient, RegisteredClientEntity> converter;


    public FlexRegisteredClientRepository(IRegisteredClientService registeredClientService,
                                          PasswordEncoder passwordEncoder) {
        this.registeredClientService = registeredClientService;
        this.converter = new RegisteredClientConverter(passwordEncoder);
    }


    @Override
    public void save(RegisteredClient registeredClient) {
        Optional.ofNullable(converter.convert(registeredClient)).ifPresent(MapperModel::save);
    }

    @Override
    public RegisteredClient findById(String id) {
        RegisteredClientEntity entity = RegisteredClientEntity.create()
                .setId(id)
                .oneById();
        return converter.transform(entity);
    }

    @Override
    public RegisteredClient findByClientId(String clientId) {
        RegisteredClientEntity entity = RegisteredClientEntity.create()
                .setClientId(clientId)
                .one();
        return converter.transform(entity);
    }
}
